import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const Login = () => import('../views/login/Login')
const Home = () => import('../views/home/Home')
const Welcome = () => import('../views/home/childComps/Welcome')
const Users = () => import('../views/home/childComps/users/Users')
const Rights = () => import('../views/home/childComps/rights/Rights')
const Roles = () => import('../views/home/childComps/roles/Roles')

const routes = [
  {
    path: '',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: Users
      },
      {
        path: '/rights',
        component: Rights
      },
      {
        path: '/roles',
        component:Roles
      }
    ]
  }
]

const router = new VueRouter({
  routes,
  mode: 'history'
})

//配置一个路由导航
router.beforeEach((to, from, next) => {
  //to 将要跳转的页面
  //from 从哪个页面跳转过来
  //next 一个函数，表示放行
  if (to.path === '/login') return next()
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) {
    return next('/login')
  } else {
    next()
  }
})

export default router
